// 用于获取数据的API
import axios from 'axios'
import {storage} from "../utils";
// import {user} from './user'
// 这个是一个axios的实例 用于和后端交互时候，需要用户信息的时候（token）
const _axios = axios.create({
  baseURL: 'http://localhost:8080/api', // 设置基础URL
  headers: {
    'Content-Type': 'application/json', // 设置默认请求头
    'token': storage.get("token"), // 添加自定义请求头
  },
});


// 获取用户的引擎数据
async function getUserEnginesFromServer() {
  try {
    const response = await _axios.get("/user-engines")
    return response.data.data
  } catch (error) {
    console.error(error)
  }
}
//   获取服务器中的默认引擎数据
async function getDefaultEnginesFromServer() {
  try {
    const response = await axios.get("./json/search_engine.json")
    return response.data
  } catch (error) {
    console.error(error)
  }
}
// 前端：获得后端的提示
async function getTip(engineName:string,key: string) {
  try {
    const response = await _axios.get("/tips/"+engineName,{
      params:{
        keyword:key
      }
    });
    return response.data.data
  } catch (error) {
    console.error(error);
  }
}

// 获取默认书签数据
async function getDefaultTagFromServer() {
  try {
    const response = await axios.get("./json/Tag.json")
    console.log(response.data)

    return response.data

  } catch (error) {
    console.error(error)
  }
}


// 从服务器中获取用户书签
async function getUserTagFromServer() {
  try {
    const responseuserId = await _axios.get("/block/getUserId")
    // console.log(responguserId.data)
    const responsedata = await _axios.get("/block/getUserTag/"+responseuserId.data.data)
    //
    return responsedata.data
  } catch (error) {
    console.error(error)
  }
}



// 从服务器获取用户最新需求搜索记录
async function getUserLastSearchChat() {
  try {
    const response = await _axios.get("/user-chatoutput")
    return response.data
  } catch (error) {
    console.error(error)
  }
}

// 从后端获取用户信息
async function  getUserInfo() : Promise<any>{
  try {
    const response = await _axios.get("/user-info")
    return response.data.data
  } catch (error: any) {
    if(error.code == "ERR_NOT_FOUND"){
      return "404"
    }else if(error.code == "ERR_UNAUTHORIZED"){
      return "401"
    }else{
        alert("token过期，请重新登录")
        storage.set("token",'')
        window.location.reload();
    }
  }

}

// 从后端获取用户搜索历史
async function  getsaveSearch() : Promise<any>{
  try {
    const response = await _axios.get("/user-saveSearch")  
    return response.data.data
  } catch (error: any) {
    
  }
}



export {  getUserEnginesFromServer, getDefaultEnginesFromServer, getTip, getDefaultTagFromServer, getUserTagFromServer, getUserLastSearchChat,getUserInfo,getsaveSearch }